﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Infrastructure.Data;
using Keepo.Models;
using AlbumDesigner.Helpers;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Drawing;
using System.IO;
using AlbumDesigner.Models.Enums;
using Keepo.Helpers;
using System.Drawing.Imaging;
using System.Threading;
using System.Web.SessionState;

namespace AlbumDesigner.Controllers
{
    public class PdfController : Controller
    {
        private AlbumContext db = new AlbumContext();
       
        [HttpPost]
        public ActionResult DeleteFiles(int AlbumPrintVersionId)
        {
            var albumPrintVersion = db.AlbumPrintVersions.Find(AlbumPrintVersionId);
            throw new Exception("tbd");
            return Json(true);
        }

        public ActionResult DownloadFile(string url)
        {
            //if this is not a pdf file
            if (Path.GetExtension(url).ToLower() != ".pdf" || url.ToLower().Contains("resources") == false)
            {
                return Json(false);
            }
            else
            {
                var filePath = Server.MapPath("~/" + url);
                return File(filePath, "application/pdf", Path.GetFileName(url));
            }
        }

        public ActionResult SetMissingPdfUrls()
        {
            var printVersions = db.AlbumPrintVersions.ToList();

            //loop through all PrintVersions without PdfUrl and set the value
            foreach (var printVersion in printVersions)
            {
                var innerPdfFileName = printVersion.Album.OrderNum + "_" + printVersion.VersionIdx + "_" + printVersion.Album.AlbumSize.Title + "_book.pdf";
                var coverPdfFileName = printVersion.Album.OrderNum + "_" + printVersion.VersionIdx + "_" + printVersion.Album.AlbumSize.Title + "_cover.pdf";
                var innerPdfDir = "resources/albums/" + printVersion.Album.AlbumId + "/pdf/inner/";
                var coverPdfDir = "resources/albums/" + printVersion.Album.AlbumId + "/pdf/cover/";

                printVersion.InnerUrl = innerPdfDir + innerPdfFileName;
                printVersion.CoverUrl = coverPdfDir + coverPdfFileName;
                db.SaveChanges();
            }

            return Json(true, JsonRequestBehavior.AllowGet);
        }


        // PdfHelper Testing
        public ActionResult CroppedImageSize(int albumId = 2, Boolean isCover = true)
        {
            using(var db = new AlbumContext())
            {
                var album = db.Albums.Find(albumId);
                var size = PdfHelper.CroppedImageSizePix(album, isCover);
                
                return Json(size, JsonRequestBehavior.AllowGet);
            }
        }
    }
}
